<template>
  <a-layout class="layout">
    <!-- 引入左侧区域 -->
    <ArticleCategory class="left-side" />

    <!-- 中间区域 -->
    <a-layout class="main-content">
      <ArticleList
          :listData="dataSource"
          :loading="loading"
          :actions="actions"
      />
    </a-layout>

    <!-- 引入右侧区域 -->
    <Rankings class="right-side" />
  </a-layout>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import ArticleCategory from './components/ArticleCategory.vue';
import ArticleList from './components/ArticleList.vue';
import Rankings from './components/Rankings.vue';
import { StarOutlined, LikeOutlined, MessageOutlined } from '@ant-design/icons-vue';

const dataSource = ref([]); // 数据源
const loading = ref(false); // 加载状态
const page = ref(1); // 当前页码
const pageSize = 10; // 每页显示的数据条数
const totalItems = 50; // 总数据条数

// 文章操作的图标和文本
const actions = ref([
  { icon: StarOutlined, text: 'Star' },
  { icon: LikeOutlined, text: 'Like' },
  { icon: MessageOutlined, text: 'Message' }
]);

// 获取数据的函数
const fetchData = async () => {
  if (loading.value || dataSource.value.length >= totalItems) return;

  loading.value = true;

  // 模拟网络延迟
  await new Promise(resolve => setTimeout(resolve, 200));

  // 生成新数据
  const newData = [];
  for (let i = 0; i < pageSize; i++) {
    newData.push({
      href: 'https://www.antdv.com/',
      title: `ant design vue part ${page.value * pageSize + i}`,
      avatar: 'https://joeschmoe.io/api/v1/random',
      description: 'Ant Design, a design language for background applications, is refined by Ant UED Team.',
    });
  }
  dataSource.value = [...dataSource.value, ...newData];
  page.value++;
  loading.value = false;
};

// 滚动事件处理函数
const handleScroll = () => {
  const mainContent = document.querySelector('.main-content');
  const scrollTop = mainContent.scrollTop;
  const clientHeight = mainContent.clientHeight;
  const scrollHeight = mainContent.scrollHeight;

  if (!loading.value && scrollTop + clientHeight >= scrollHeight - 1) {
    fetchData();
  }
};

// 添加和移除事件监听器
onMounted(() => {
  fetchData(); // 初次加载数据
  window.addEventListener('scroll', handleScroll);
});

onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll);
});
</script>

<style scoped>
.layout {
  min-height: 100vh;
  display: flex;
}

.left-side {
  flex: 3; /* 左侧区域占3份 */
}

.main-content {
  flex: 5; /* 中间区域占5份 */
  padding: 16px;
  background: #ffffff; /* 中间区域背景 */
  margin: 0 16px; /* 与左右区域的间隔 */
  overflow: hidden; /* 隐藏溢出的内容，不显示滚动条 */
}
.right-side {
  flex: 2; /* 右侧区域占3份 */
}
</style>
